<template>
  <div class="homework-container">
    <el-card class="homework-list">
      <template #header>
        <div class="card-header">
          <span>我的作业</span>
        </div>
      </template>
      
      <el-table :data="homeworkList" style="width: 100%">
        <el-table-column prop="title" label="作业标题" />
        <el-table-column prop="description" label="作业描述" show-overflow-tooltip />
        <el-table-column prop="teacherName" label="教师" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" link @click="doHomework(scope.row)">
              {{ scope.row.status === 0 ? '做作业' : '查看' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 做作业对话框 -->
    <el-dialog v-model="homeworkDialogVisible" title="作业详情" width="60%">
      <template v-if="currentHomework">
        <h3>{{ currentHomework.title }}</h3>
        <p>{{ currentHomework.description }}</p>
        
        <el-form :model="answerForm" label-width="100px">
          <div v-for="(question, index) in currentHomework.questions" :key="index" 
               class="question-item">
            <h4>题目 {{ index + 1 }}</h4>
            <p>{{ question.questionContent }}</p>
            
            <!-- 添加知识点显示 -->
            <div v-if="currentHomework.status === 2 && question.knowledgePoint" class="knowledge-point-info">
              <el-tag type="success" effect="plain">
                相关知识点：{{ question.knowledgePoint.name }}
              </el-tag>
              <p class="knowledge-point-desc">{{ question.knowledgePoint.description }}</p>
            </div>
            
            <!-- 选择题 -->
            <template v-if="question.questionType === 1">
              <el-radio-group v-model="answerForm[question.id]" 
                             :disabled="currentHomework.status === 2">
                <template v-if="hasValidOptions(question.questionOptions)">
                  <div v-for="(option, optIndex) in validOptions(question.questionOptions)" 
                       :key="optIndex">
                    <el-radio :label="String.fromCharCode(65 + optIndex)">
                      {{ option.content }}
                    </el-radio>
                  </div>
                </template>
                <template v-else>
                  <div class="error-message">
                    <el-alert
                      title="此题选项配置有误，请联系教师"
                      type="warning"
                      :closable="false"
                    />
                  </div>
                </template>
              </el-radio-group>
            </template>
            
            <!-- 填空题 -->
            <template v-else-if="question.questionType === 2">
              <el-input v-model="answerForm[question.id]" 
                        :disabled="currentHomework.status === 2"
                        placeholder="请输入答案" />
            </template>

            <!-- 简答题 -->
            <template v-else-if="question.questionType === 3">
              <el-input v-model="answerForm[question.id]" 
                        type="textarea" 
                        :rows="4"
                        :disabled="currentHomework.status === 2"
                        placeholder="请输入答案" />
            </template>

            <!-- 综合题 -->
            <template v-else-if="question.questionType === 4">
              <el-input v-model="answerForm[question.id]" 
                        type="textarea" 
                        :rows="8"
                        :disabled="currentHomework.status === 2"
                        placeholder="请输入答案（可以包含文字说明、计算过程等）" />
            </template>

            <!-- 未知题型 -->
            <template v-else>
              <div class="error-message">
                <el-alert
                  title="未知的题目类型"
                  type="warning"
                  :closable="false"
                />
              </div>
            </template>
            
            <!-- 显示批改结果 -->
            <template v-if="currentHomework.status === 2 && question.studentAnswer">
              <div class="grade-result">
                <p class="score">得分：{{ question.studentAnswer.score }}</p>
                <p class="comment">教师评语：{{ question.studentAnswer.teacherComment }}</p>
              </div>
            </template>
          </div>
        </el-form>
        
        <div class="dialog-footer">
          <el-button @click="homeworkDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitAnswers" 
                     v-if="currentHomework.status === 0">
            提交作业
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import useUserInfoStore from '@/stores/userInfo'
import { useTokenStore } from '@/stores/token'
import { 
  getStudentHomeworks, 
  getHomework, 
  getQuestions, 
  submitAnswer,
  updateHomeworkStatus,
  getHomeworkKnowledgePoints
} from '@/api/homework'

const router = useRouter()
const userStore = useUserInfoStore()
const tokenStore = useTokenStore()
const loading = ref(false)
const homeworkList = ref([])
const homeworkDialogVisible = ref(false)
const currentHomework = ref(null)
const answerForm = ref({})

async function fetchHomeworkList() {
  try {
    loading.value = true
    console.log('检查token...')
    if (!tokenStore.token) {
      console.error('未登录，跳转到登录页面')
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }

    console.log('开始获取用户信息...')
    // 确保获取到用户信息
    if (!userStore.info?.id) {
      console.log('用户信息不存在，尝试获取...')
      const userInfo = await userStore.getUserInfo()
      console.log('获取到的用户信息:', userInfo)
      if (!userInfo) {
        console.error('获取用户信息失败，跳转到登录页面')
        ElMessage.error('获取用户信息失败，请重新登录')
        router.push('/login')
        return
      }
    }

    // 检查用户角色
    if (userStore.info.role !== 0) {
      console.error('非学生用户无法访问此页面')
      ElMessage.error('只有学生可以访问此页面')
      router.push('/')
      return
    }

    console.log('开始获取作业列表，用户ID:', userStore.info.id)
    const response = await getStudentHomeworks(userStore.info.id)
    console.log('获取到的作业列表:', response)
    homeworkList.value = response.data
  } catch (error) {
    console.error('获取作业列表失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response)
      if (error.response.status === 401) {
        ElMessage.error('登录已过期，请重新登录')
        router.push('/login')
      } else {
        ElMessage.error(error.response.data?.message || '获取作业列表失败')
      }
    } else {
      console.error('网络错误:', error.message)
      ElMessage.error('网络错误，请检查网络连接')
    }
  } finally {
    loading.value = false
  }
}

// 做作业
const doHomework = async (homework) => {
  try {
    console.log('开始获取作业详情，作业ID:', homework.id)
    const res = await getHomework(homework.id)
    console.log('获取到的作业详情:', res)
    currentHomework.value = res.data
    
    // 获取作业的知识点信息
    if (currentHomework.value.status === 2) {
      try {
        console.log('开始获取作业知识点信息，作业ID:', homework.id)
        const knowledgePointsRes = await getHomeworkKnowledgePoints(homework.id)
        console.log('获取到的知识点响应:', knowledgePointsRes)
        
        if (knowledgePointsRes.code === 0 && knowledgePointsRes.data) {
          console.log('知识点数据:', knowledgePointsRes.data)
          
          // 将知识点信息关联到对应的题目
          currentHomework.value.questions.forEach(question => {
            console.log('处理题目:', question.id, '知识点ID:', question.knowledgePointId)
            const knowledgePoint = knowledgePointsRes.data.find(
              kp => kp.id === question.knowledgePointId
            )
            console.log('找到的知识点:', knowledgePoint)
            if (knowledgePoint) {
              question.knowledgePoint = {
                name: knowledgePoint.name,
                description: knowledgePoint.description
              }
              console.log('设置题目知识点:', question.knowledgePoint)
            } else {
              console.log('未找到题目对应的知识点')
            }
          })
        } else {
          console.warn('获取知识点响应异常:', knowledgePointsRes)
        }
      } catch (error) {
        console.error('获取作业知识点信息失败:', error)
        if (error.response) {
          console.error('错误响应:', error.response.data)
          ElMessage.warning('获取知识点信息失败：' + (error.response.data?.message || '未知错误'))
        }
      }
    } else {
      console.log('作业未批改，不获取知识点信息. 当前状态:', currentHomework.value.status)
    }
    
    // 初始化答案表单
    answerForm.value = {}
    currentHomework.value.questions.forEach(question => {
      if (question.studentAnswer) {
        answerForm.value[question.id] = question.studentAnswer.answerContent
      } else {
        answerForm.value[question.id] = ''
      }
    })
    
    homeworkDialogVisible.value = true
  } catch (error) {
    console.error('获取作业详情失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response)
      ElMessage.error(error.response.data?.message || '获取作业详情失败')
    } else {
      console.error('网络错误:', error.message)
      ElMessage.error('网络错误，请检查网络连接')
    }
  }
}

// 提交作业答案
const submitAnswers = async () => {
  try {
    // 检查是否所有题目都已作答
    const unanswered = currentHomework.value.questions.some(
      q => !answerForm.value[q.id]
    )
    
    if (unanswered) {
      ElMessage.warning('请完成所有题目')
      return
    }

    // 提交每道题的答案
    for (const question of currentHomework.value.questions) {
      await submitAnswer({
        homeworkId: currentHomework.value.id,
        questionId: question.id,
        studentId: userStore.info.id,
        answerContent: answerForm.value[question.id]
      })
    }

    // 更新作业状态为已提交（状态码1）
    await updateHomeworkStatus(currentHomework.value.id, 1)

    ElMessage.success('作业提交成功')
    homeworkDialogVisible.value = false
    fetchHomeworkList()
  } catch (error) {
    console.error('作业提交失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response)
      ElMessage.error(error.response.data?.message || '作业提交失败')
    } else {
      console.error('网络错误:', error.message)
      ElMessage.error('网络错误，请检查网络连接')
    }
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'info',    // 未完成
    1: 'warning', // 已提交
    2: 'success'  // 已批改
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '未完成',
    1: '已提交',
    2: '已批改'
  }
  return texts[status] || '未知'
}

// 解析题目选项
const parseQuestionOptions = (optionsStr) => {
  if (!optionsStr) return [];
  try {
    return JSON.parse(optionsStr);
  } catch (error) {
    console.error('解析题目选项失败:', error);
    console.error('原始选项字符串:', optionsStr);
    return [];
  }
}

// 获取有效的选项（用于v-for渲染）
const validOptions = (optionsStr) => {
  const options = parseQuestionOptions(optionsStr);
  return options.filter(opt => opt && opt.content);
}

// 检查是否有有效选项
const hasValidOptions = (optionsStr) => {
  const options = validOptions(optionsStr);
  return options.length > 0;
}

// 获取题型文本
const getQuestionTypeText = (type) => {
  const types = {
    1: '选择题',
    2: '填空题',
    3: '简答题',
    4: '综合题'
  }
  return types[type] || '未知题型';
}

onMounted(() => {
  fetchHomeworkList()
})
</script>

<style scoped>
.homework-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.question-item {
  border-bottom: 1px solid #eee;
  padding: 20px 0;
}

.question-item:last-child {
  border-bottom: none;
}

.grade-result {
  margin-top: 15px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.score {
  color: #67c23a;
  font-weight: bold;
}

.comment {
  color: #606266;
  margin-top: 5px;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}

.error-message {
  margin-top: 10px;
}

.knowledge-point-info {
  margin: 10px 0;
  padding: 10px;
  background-color: #f0f9eb;
  border-radius: 4px;
}

.knowledge-point-desc {
  margin: 8px 0 0 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.4;
}
</style> 